var RNFS = require('react-native-fs');
import React, { Component } from 'react';
import { Modal, View, Text, TextInput, TouchableHighlight, StyleSheet, TouchableOpacity, Image, Pressable, Dimensions,Alert,ImageBackground,Platform,ToastAndroid} from 'react-native'
import { RadioGroup, RadioButton } from 'react-native-flexi-radio-button'
import { color } from 'react-native-reanimated';
import RNFileSelector from 'react-native-file-selector';
import Video from 'react-native-video';
import {Videos,videopath,userpath} from '../../../../utils/path'
import FileUtil from '../../../../utils/file'
// import ScreenOrientation, { PORTRAIT, LANDSCAPE } from "react-native-orientation-locker/ScreenOrientation";
import Orientation from 'react-native-orientation-locker';
import Slider from '@react-native-community/slider';
import {  getuser } from '../../../../actions/actionCreators'
import store from '../../../../store/configureStore'
let screenWidth = Dimensions.get('window').width;
let screenHeight = Dimensions.get('window').height;
console.log(screenWidth + "   " + screenHeight + "带有小数");
class videomodel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // modalVisible:f
            videos: [],
            text: "0",
            path: "",
            isPlay: 0,
            duration: 0,
            currentTime: "",
            paused: "",
            videoindex:"",
            videopath:"",
            autotime:'1',
            pagesize: 3,
            pageindex: 0,
            newvideos:"",
            videoWidth:'',
            videoHeight:""
           


        }
    }
    onSelect(index, value) {
        console.log(index,value)
        this.setState({
            text: value
        })
    }
    getvideofile = () => {
        RNFileSelector.Show(
            // 外部存储卡的数据内容复制到安卓内置内存的某个文件夹,,说文件夹大于5M就没办法上传
            {
                path: '/storage/',//可以自定义路径
                title: '请选择文件',
                onDone: async (path) => {
                    var index = path.lastIndexOf("."); // lastIndexOf("/")  找到最后一个  /  的位置
                    var fileType = path.substr(index + 1); // substr() 截取剩余的字符，即文件名doc
                    if (fileType!=='mp4' && fileType!=='rmvb' && fileType!=='avi' && fileType!=='ts') {
                        ToastAndroid.showWithGravity('请选择视频文件文件',ToastAndroid.SHORT,
                        ToastAndroid.CENTER)  
                        return
                    }
                    // 假如不可重名
                    this.setState({ path: path })
                    console.log(this.state.path)
                        // 如果存在看看path路径是否在excel文件下存在，不存在就开始复制，存在就提醒姨存在
            //切割路径的最后一个文件名获取到这个excel文件名
            var filename = path.substring(path.lastIndexOf('/'))
            const fileisExists = await FileUtil.isExistFile(Videos + filename);
            console.log(fileisExists)
            if (fileisExists) {//判断特定目录【/data/user/0/com.awesomeproject/files/AnsweringMachine】存在文件夹有没有这个【demo.xlsx】文件，没有就复制，有就不复制
                Alert.alert('提示', '该文件名已经在库里存在，请重新选择', [
                    { text: '确定', onPress: () => console.log('OK Pressed') },
    
                ]);
                RNFS.readDir(filePath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
                    .then((result) => {
                        console.log('已存在文件', result);
                        // stat the first file
                        return Promise.all([RNFS.stat(result[0].path), result[0].path]);
                    })

            } else {
                RNFS.copyFile(path, Videos + filename).then(res => {
                    // 复制成功要要解析当前加的视频数据获得相关数据在在videopath里面记录数据
                    console.log(res)
                    Alert.alert('提示', '保存文件成功', [
                        { text: '确定', onPress: () => console.log('OK Pressed') },

                    ]);
                    this.componentDidMount()

                    // RNFS.readFile(videopath, 'utf8').then(res => {
                    //     console.log(res)
                    //     var arr = JSON.parse(res)
                    //     let currentid;
                    //     if (arr.length < 1) {
                    //         currentid = 1
                    //     } else {
                    //         currentid = arr.length + 1
                    //     }
                    //     var obj={id:currentid,videopath:Videos + filename}
                    //     arr.push(obj)
                    //     RNFS.writeFile(videopath, JSON.stringify(arr), 'utf8')
                    //         .then((success) => {
                    //             console.log('FILE WRITTEN!');
                    //             Alert.alert('提示', '保存文件成功', [
                    //                 { text: '确定', onPress: () => console.log('OK Pressed') },

                    //             ]);
                    //         })
                    //         .catch((err) => {
                    //             console.log(err.message);
                    //         })


                    // })



                }).catch(e => {
                    console.log(e)
                })
            }

                },
                onCancel: () => {
                    console.log('cancelled')
                }
            }
        )
    }

    // 视频播放存在的方法

    onLoad = (data) => {
        this.setState({ duration: data.duration });
    };

    onProgress = (data) => {
        this.setState({ currentTime: data.currentTime });
    };

    onEnd = () => {
        this.setState({ paused: true });
    };

    onAudioBecomingNoisy = () => {
        this.setState({ paused: true })
    };

    onAudioFocusChanged = ({ event: { hasAudioFocus: boolean } }) => {
        this.setState({ paused: !event.hasAudioFocus })
    };
    _onPressvideo=(index,item)=>{
        console.log(index,item)
        this.setState({ videoindex: index + 1,videopath:item.path})

    }
    delvideo=async ()=>{
        await RNFS.unlink(this.state.videopath)
            .then(() => {
                console.log('FILE DELETED');
                this.componentDidMount()

            })
            .catch((err) => {
                console.log(err.message);
            })

    }
    onChangeText=(text)=>{
        const newText = text.replace(/[^\d]+/, '');
        this.setState({autotime:newText})
    }
    setuser=()=>{
        // 读取user.txt
        RNFS.readFile(userpath, 'utf8').then(res => {
          var arr=JSON.parse(res)
          arr[0]['autotime']=this.state.autotime//自动播放时间
          arr[0]['issort']=this.state.text//0.顺序，1随机
          console.log(arr) 
            RNFS.writeFile(userpath,JSON.stringify(arr), 'utf8')
                .then((success) => {
                    const action = getuser(arr)
                    store.dispatch(action)
                    console.log('FILE WRITTEN!');
                    ToastAndroid.showWithGravity('保存成功', ToastAndroid.SHORT,
                    ToastAndroid.CENTER)

                })
                .catch((err) => {
                    console.log(err.message);
                })


        }).catch(err=>{
            console.log(err)
        })
    }
    componentDidMount=async ()=>{
        // 读取库里的特定路径的视频资源
        RNFS.readDir(Videos) // On Android, use "RNFS.DocumentDirectoryPath（内置存储）" (MainBundlePath is not defined)
        .then((result) => {
            console.log('GOT RESULT', result);
           let newvideos=  result.slice(this.state.pageindex * this.state.pagesize, (this.state.pageindex + 1) * this.state.pagesize)
            this.setState({ videos: result,newvideos: newvideos})

            // stat the first file
        })

    }
    onPresspre = () => {
        console.log(11)
        let newvideos=  this.state.videos.slice((this.state.pageindex -1) * this.state.pagesize, (this.state.pageindex-1 + 1) * this.state.pagesize)
        if (this.state.pageindex > 0) {
            this.setState({ pageindex: this.state.pageindex - 1,newvideos:newvideos })
        } else {
            ToastAndroid.showWithGravity('已是第一页', ToastAndroid.SHORT,
            ToastAndroid.CENTER)
        }
    };
    onPressnext = () => {
        let pageMax = Math.ceil(this.state.videos.length / this.state.pagesize)
        console.log(this.state.pageindex, pageMax)
        let newvideos=  this.state.videos.slice((this.state.pageindex + 1) * this.state.pagesize, (this.state.pageindex + 1+1) * this.state.pagesize)
        if (this.state.pageindex+1 < pageMax) {
            this.setState({ pageindex: this.state.pageindex + 1,newvideos:newvideos })
        } else {
            ToastAndroid.showWithGravity('已是最后一页', ToastAndroid.SHORT,
            ToastAndroid.CENTER)
        }

    };
    onLayout = event => {
        //获取根View的宽高
        let { width, height } = event.nativeEvent.layout;
        console.log("通过onLayout得到的宽度：" + width);
        console.log("通过onLayout得到的高度：" + height);
    
        // 一般设备横屏下都是宽大于高，这里可以用这个来判断横竖屏
        let isLandscape = width > height;
        if (isLandscape) {
          this.setState({
            videoWidth: width,
            videoHeight: height,
          });
        } else {
          this.setState({
            videoWidth: width,
            videoHeight: (width * 9) / 16,
          });
        }
        // Orientation.unlockAllOrientations();
      };
    
    render() {
        // console.log(this.props)
        // const {navigate} = this.props.navigation;//子组件不能访问      
        return (
            <Modal
                animationType="slide"
                transparent={true}
                // 继承属性和方法
                visible={this.props.videomodalVisible}
                onRequestClose={() => {
                    Alert.alert("Modal has been closed.");
                }}
            >
             <View style={{  
        flexDirection:"row",
        justifyContent: "center",
        alignItems: "center",
        width:"100%",
        height:"100%",
        // padding:30,

        
        }} onLayout={this.onLayout}>
             <ImageBackground style={{ ...styles.modalView1,width: this.state.videoWidth*0.95 }}
                                        source={require('../../../../../assets/imgs/a1/background.png')}
                                        imageStyle={{ resizeMode: 'stretch' }}

                                    >

                    <Text style={{ color: "#fff", fontSize: 20,marginTop:10 }}>视频管理</Text>
                    <Pressable style={{ position: "absolute", right: 25, top: 15,zIndex:100 }} onPress={() => { this.props.handvideocloseVisible(false) }}><Image
                        style={{ width: 40, height: 40 }}
                        source={require('../../../../../assets/imgs/close.png')}

                    /></Pressable >

                    <View style={[styles.choosefengmian,{width:this.state.videoWidth*0.85}]}>
                        <TouchableOpacity
                            style={styles.leftLogo1}
                            onPress={this.onPresspre}
                        >
                            <Image
                                style={styles.imgs1}
                                source={require('../../../../../assets/imgs/houtui.png')} />
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={styles.rightLogo1}
                            onPress={this.onPressnext}

                        >
                            <Image
                                style={styles.imgs1}
                                source={require('../../../../../assets/imgs/qianjin.png')} />
                        </TouchableOpacity>
                        {/* <View style={styles.images}><Text style={{ color: "#fff" }}>不使用封面</Text></View> */}
                        {/* 如果没有视频显示文字 */}
                        {
                          this.state.videos.length >= 1 ? (
                          this.state.newvideos.map((item,index) => {
                                    return (
                                        <View style={[styles.images,this.state.videoindex == index + 1 ? { borderColor: "#CC985D" } : '']} key={index}>
                                            {/* <Image
                                                                    style={styles.a1}
                                                                    source={require('../../../../../assets/imgs/fm1.jpg')}
                                                                /> */}
                                            <TouchableOpacity onPress={() => { this._onPressvideo(index, item) }} style={{width:"100%",height:"100%"}}>
                                                <Video
                                                    // https://www.npmjs.com/package/react-native-video#source
                                                    // source={ require( '../../../../../assets/imgs/video.mp4')}   // Can be a URL or a local file.
                                                    source={{ uri: `file://${item.path}` }}   // Can be a URL or a local file.
                                                    // poster='https://baconmockup.com/300/200/'
                                                    // poster='file:///storage/emulated/0/Download/timg.jpg'
                                                    // posterResizeMode='stretch'
                                                    resizeMode="stretch"           // 视频的自适应伸缩铺放行为，contain、stretch、cover
                                                    style={styles.backgroundVideo}//自身样式
                                                    repeat={true}                // 是否重复播放
                                                    rate={this.state.isPlay ? 1 : 0}   // 控制播放速率，0 代表不播放暂停, 1代表正常速度播放normal.
                                                    paused={false}               // true代表暂停，默认为false
                                                    onLoad={this.onLoad}//加载媒体并准备播放时调用的回调函数。
                                                    onProgress={this.onProgress}//视频播放过程中每个间隔进度单位调用的回调函数
                                                    onEnd={this.onEnd}//视频播放结束时的回调函数
                                                    onAudioBecomingNoisy={this.onAudioBecomingNoisy}//音频变得嘈杂时的回调 - 应暂停视频
                                                    onAudioFocusChanged={this.onAudioFocusChanged}//音频焦点丢失时的回调 - 如果焦点丢失则暂停

                                                />
                                            </TouchableOpacity>


                                        </View>
                                    )
                                })
                            ) : (<Text style={{ color: "#fff", marginTop: 200 }}>未找到视频，如有需要，您可以点击添加按钮，从U盘或其他位置添加。</Text>)

                        }

                    </View>
                    <View style={styles.videobuttons}>
                        <Pressable
                        disabled={this.state.videoindex?false : true}
                        onPress={() => {
                            this.delvideo()
                          }}

                        >
                            <Text style={{ ...styles.btns, fontSize: 18, color: "#fff", borderRadius: 8, }}>
                                删除
                               </Text>
                        </Pressable>
                        <Pressable
                        disabled={this.state.videoindex?false : true}
                        onPress={() => {
                             this.props.enterFullScreen(this.state.videopath)
                        }}

                        >
                            <Text style={{ ...styles.btns, fontSize: 18, color: "#fff", borderRadius: 8, }}>
                                播放
                               </Text>
                        </Pressable>
                        <Pressable
                            onPress={() => { this.getvideofile() }}
                        >
                            <Text style={{ ...styles.btns, fontSize: 18, color: "#fff", borderRadius: 8, }} >
                                添加
                                </Text>
                        </Pressable>
                    </View>

                    <View style={styles.videobofang}>
                        <View style={{ color: "#fff", lineHeight: 20,justifyContent:"center",alignItems:"center",display:"flex",flexDirection:"row",marginRight:10 }}><Text style={{color: "#fff"}}>停止操作</Text>
                        <TextInput
                                style={{  borderColor: '#62AEDD', backgroundColor: "#3070AF", borderWidth: 1, color: "#fff", width: 30,height:33, fontSize: 12,lineHeight:10}}
                                onChangeText={text => this.onChangeText(text)}
                                keyboardType='numeric'
                                value={this.state.autotime}
                                clearButtonMode='while-editing'
                                selectionColor="black"
                                defaultValue={'1'}

                        />
                        <Text style={{color: "#fff"}}>分钟后开始自动播放视频， 0表示不会自动播放视频    </Text>
                        </View>

                        <Pressable
                     onPress={() => { this.setuser() }}

                        >
                            <Text style={{ ...styles.btns, fontSize: 18, color: "#fff", borderRadius: 8, }} >
                                屏保设置
                            </Text>
                        </Pressable>

                    </View>
                    <RadioGroup
                        onSelect={(index, value) => this.onSelect(index, value)}
                        style={styles.radios}
                        color='#fff'
                        selectedIndex={0}
                    // highlightColor='#ccc8b9'
                    >
                        <RadioButton value={'0'} color='#fff' activeColor='' highlightColor=''>
                            <Text style={{ color: "#fff" }}>顺序播放</Text>
                        </RadioButton>

                        <RadioButton value={'1'} color='#fff'>
                            <Text style={{ color: "#fff" }}>随机播放</Text>
                        </RadioButton>

                    </RadioGroup>


                </ImageBackground>
             </View>
            </Modal>
        );
    }
}

export default videomodel;
const styles = StyleSheet.create({
    // model样式
    modalView1: {
        // backgroundColor:"red",
        borderRadius: 20,

        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    choosefengmian: {
        height: '42%',
        marginLeft: 10,
        marginRight: 10,
        display: "flex",
        flexDirection: 'row',
        flexWrap: "wrap",
        justifyContent: 'space-around',
        alignItems: "center"

    },
    leftLogo1: {
        position: "absolute",
        left: -55,
        width: 80,
        height: 80,
        top: 100

    },
    rightLogo1: {
        position: "absolute",
        right: -35,
        width: 80,
        height: 80,
        top: 100


    },
    imgs1: {

        height: 100,
        width: 100
    },
    images: {
        width: '25%',
        height: '80%',
        marginTop: 10,

        borderColor: '#78FAF6',
        borderWidth: 2,
        shadowColor: "#78FAF6",
        display: 'flex',
        justifyContent: 'center',
        alignItems: "center"
        // shadowOffset: {
        //     width: 0,
        //     height: 0
        // },
        // shadowOpacity: 0.25,
        // shadowRadius: 3.84,
        // elevation: 5
        // flex:1
    },
    backgroundVideo: {
        width: '99%',
        height: '99%',
        padding: 2,


    },
    openButton: {
        backgroundColor: '#CC975D',
        borderRadius: 5,
        padding: 2,
        elevation: 2,
        marginTop: 20,
        width: 100,
        fontSize: 8,
    },
    videobuttons: {
        width: '80%',
        paddingRight: 10,
        paddingLeft: 10,
        // marginTop:15,
        display: "flex",
        justifyContent: "space-around",
        flexDirection: "row",//rn默认column

    },

    btns: {
        backgroundColor: '#CC975D',
        width: 140,
        height: 40,
        // flex:1,
        textAlign: 'center',
        lineHeight: 40,

        fontWeight: 'bold'
    },
    videobofang: {
        // display:"flex",
        flexDirection: "row",//rn默认column
        marginTop: 10,

        justifyContent: "space-around",
    },
    radios: {
        flexDirection: "row",//rn默认column
        color: "#fff"

    },


})
